import './imports';
import Header from '../components/Header';
import NewsFrame from '../components/Iframe';
import Follow from '../components/Follow';
import { getUrlQueryValue } from '../libs/utils';
((doc) => {
    const oApp = doc.querySelector('#app');
    const currentNew = JSON.parse(localStorage.getItem('currentNew'));
    const followedList = JSON.parse(localStorage.getItem('followedList') || '[]');
    let oFollow = null;
    const init = () => {
        render();
        bindEvent();
    }

    function render() {
        const headerTpl = Header.tpl({
            url: getUrlQueryValue('path'),
            title: '新闻详情',
            showLeftIcon: true,
            showRightIcon: false
        });
        const newsFrameTpl = NewsFrame.tpl(currentNew.url);
        const followTpl = createFollowTpl();
        oApp.innerHTML += (headerTpl + newsFrameTpl + followTpl);
    }

    function bindEvent() {
        oFollow = doc.querySelector('.follow');
        oFollow.addEventListener('click', setFollow, false)
    }

    function createFollowTpl() {
        const isExist = followedList.find(function (item) {
            return item.uniquekey === currentNew.uniquekey
        })
        return isExist ? Follow.follow() : Follow.unfollow()
    }
    function setFollow() {
        const className = oFollow.className;
        oFollow.className = 'follow iconfont icon-'
        switch (className) {
            case 'follow iconfont icon-star':
                oFollow.className += 'star-o';
                doFollow(false);
                break;
            case 'follow iconfont icon-star-o':
                oFollow.className += 'star';
                doFollow(true);
                break;
            default:
                break;
        }
    }
    function doFollow(status) {
        let followedList = JSON.parse(localStorage.getItem('followedList') || '[]');
        if (status) {
            followedList.push(currentNew);
        } else {
            followedList = followedList.filter(item => item.uniquekey !== currentNew.uniquekey);
        }
        localStorage.setItem('followedList', JSON.stringify(followedList));
    }
    init();
})(document);